
<template>
  <div class="input-bottom-title" @click="startRecording">
    <!--            <div class="title">音频输出格式:如我想咨询太原晋祠文化介绍/最佳路线/景点游览/特色美食/交通信息</div>-->
    <div class="input-box">
      <div class="answer">
        <div class="send">
          <img v-if="isclick" style="width: 18px;height: 18px;margin-right: 10px" src="@/assets/images/notLoggedIn/video_group@2x.png" >
          <img v-else  style="width: 18px;height: 18px;margin-right: 10px" src="@/assets/images/notLoggedIn/voice@2x.png">
        </div>
        <div class="title">请点击说话提问问题</div>


      </div>
    </div>
  </div>
</template>
<script setup>
import api from "@/service/TouristHomepage";
import {ref} from "vue";
import { Buffer } from "buffer";
import Recorder from 'js-audio-recorder'
import axios from "axios";
import {fileUploadUrl} from "@/hook/setting";
import {useHistoryStore} from "@/store/history";
import {useCulturalSelectionStore} from "@/store/culturalSelection";
// 传给父级
const emit = defineEmits(["changeVioce"]);
const isclick = ref(false);
function changeVioce(){
  window.Buffer = Buffer;
  recorder.value=new Recorder({
    sampleBits: 16, // 采样位数，支持 8 或 16，默认是 16
    sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，Chrome 是 48000
    numChannels: 1, // 声道数，支持 1 或 2， 默认是 1
    // // 配置项
    // sampleBits: 16, // 采样位数 默认16
    // sampleRate: 44100, // 采样率 默认44100
    // numChannels: 1, // 声道数 默认1
    // mimeType: 'audio/wav', // 音频类型 默认audio/wav
    // onprocess: (duration, fileSize) => {
    //   console.log('onprocess', duration, fileSize)
    // },
    // onprogress: (payload) => {
    //   console.log('onprogress', payload)
    // }
  })
  Recorder.getPermission().then(
      () => {
        console.log("开始录音");
        recorder.value.start(); // 开始录音
      },
      (error) => {
        this.$message({
          message: '请先允许该网页使用麦克风',
          type: 'info'
        })


      }
  );

}
const recorder = ref(null)
function  startRecording() {
  isclick.value=!isclick.value;

  if(isclick.value){
    changeVioce()

  }
  if(!isclick.value){
    handleStop();
    setTimeout(()=>{
      handlePlay();
    },1000)


  }


}
const timer=ref( null);
const playTime=ref( null);
function  handlePlay() {
  console.log('播放录音')
  recorder.value.play() // 播放录音

  // 播放时长
  timer.value = setInterval(() => {
    try {
      playTime.value = recorder.value.getPlayTime()
    } catch (error) {
      timer.value = null
    }
  }, 100)
}
const currentInfoType=ref(null)
async function handleStop() {
  console.log('停止录音')
  recorder.value.stop() // 停止录音
  const blob = recorder.value.getPCMBlob(); // 获取 pcm 格式音频数据
  const newBlob = new Blob([blob]);
  // 此处获取到 blob 对象后需要设置 fileName 满足项目上传需求，这里选择把 blob 包装成 file 塞入 formData
  const fileOfBlob = new File([newBlob], new Date().getTime() + ".pcm");
  const formData = new FormData();
  formData.append("file", fileOfBlob);
  const response = await axios({
    url: fileUploadUrl,
    method: 'POST',
    // responseType: 'blob', // 重要：指定响应类型为二进制流
    headers: {
      'Content-Type': 'application/json',
      // 如果需要认证，可以在这里添加认证头
      // 'Authorization': `Bearer ${token}`
    },
    data: formData
  });
  console.log("音频转码----",response)
  if(response.data.code==200){
  //   传给父级
    emit("changeVioce",response.data.data)
  //   返回当前语音模块
    currentInfoType.value=response.data.data.info;
    useCulturalSelectionStore().setCulturalSelectionList(response.data.data.info)
  //   存入历史记录模块
    if(useHistoryStore().historyList && useHistoryStore().historyList.length>0){
      let arr=useHistoryStore().historyList;
      arr.push(response.data.data.question)
      useHistoryStore().setHistoryList(arr)
    }else {
      useHistoryStore().setHistoryList([response.data.data.question])
    }


  }
  // api.fileUpload(formData).then(res=>{
  //   console.log('赵琳----',res)
  // })
}
</script>
<style scoped lang="scss">
.input-bottom-title{
  cursor: pointer;
  .title{
    font-family: DingliesongtypefaceRegular;
    height: 16px;
    font-weight: 400;
    font-size: 16px;
    color: #E9DCD5;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
  .input-box{
    width: 100%;
    //width: 1200px;
    height: 60px;
    background: #FFFFFF;
    box-shadow: 0px 4px 13px 0px rgba(238,142,58,0.13);
    border-radius: 10px 10px 10px 10px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-top: 25px;
    .answer{
      height: 16px;
      display: flex;
      align-items: center;
    }

  }
}
</style>